# 系统接口
from django.http import JsonResponse, HttpResponse
from web.models import Version, VersionDesc
from web import utils
from django import forms
from django.forms import model_to_dict
import json
from django.views.decorators.csrf import csrf_exempt
from django.middleware.csrf import get_token


tools = utils.Utils()

class VersionForm(forms.ModelForm):
    class Meta:
        model = Version
        fields = ['version', 'download_url']

# 版本
@csrf_exempt
def Versions(request):
    """
    创建版本
    """
    if request.method == "POST":
        request_data = VersionForm(request.POST)

        if request_data.is_valid():
            # 保存数据
            data = request_data.save()
            new_data = model_to_dict(data)
            new_data["create_time"] = data.create_time.strftime("%Y-%m-%d %H:%M:%S")
            return JsonResponse({
                'code': 200,
                'msg': '创建成功',
                'data': new_data
            })
        error = tools.Forms_GetError(request_data)
        return JsonResponse({
            'code': 400,
            'msg': error[1],
            'data': error[0]
        })

    # 请求方式错误
    return JsonResponse({
        'code': 400,
        'msg': '请求方式错误',
        'data': {}
    })


class VersionDescForms(forms.ModelForm):
    class Meta:
        model = VersionDesc
        fields = '__all__'

@csrf_exempt
def VersionD(request):
    if request.method == "POST":
        request_data = VersionDescForms(request.POST)
        if request_data.is_valid():
            # 保存数据
            data = request_data.save()
            new_data = model_to_dict(data)
            new_data["type"] = data.get_type_display()
            new_data["version"] = data.version.version
            del new_data["id"]
            return JsonResponse({
                'code': 200,
                'msg': '创建成功',
                'data': new_data
            })
        error = tools.Forms_GetError(request_data)
        return JsonResponse({
            'code': 400,
            'msg': error[1],
            'data': error[0]
        })
    elif request.method == "GET":
        version = request.GET.get("version", "")
        if version:
            data = VersionDesc.objects.filter(version=version)
            new_data = []
            for i in data:
                a = model_to_dict(i)
                a["type"] = i.get_type_display()
                del a["id"]
                del a["version"]
                new_data.append(a)
            return JsonResponse({
                'code': 200,
                'msg': '获取成功',
                'data': new_data
            })
    return JsonResponse({
        'code': 400,
        'msg': '请求方式错误',
        'data': {}
    })

def VersionList(request):
    data = Version.objects.all().order_by('-id')
    new_data = []
    for i in data:
        a = model_to_dict(i)
        a["create_time"] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        a["contents"] = []
        for j in VersionDesc.objects.filter(version=i):
            a1 = model_to_dict(j)
            a1["type"] = j.get_type_display()
            del a1["id"]
            del a1["version"]
            a["contents"].append(a1)
        new_data.append(a)

    return JsonResponse({
        'code': 200,
        'msg': '获取成功',
        'data': new_data
    })

# 当前版本
def CurrentVersion(request):
    data = Version.objects.all().order_by('-id').first()
    if data:
        data = model_to_dict(data)
        data["contents"] = []
        for j in VersionDesc.objects.filter(version=data["version"]):
            a1 = model_to_dict(j)
            a1["type"] = j.get_type_display()
            del a1["id"]
            del a1["version"]
            data["contents"].append(a1)
        return JsonResponse({
            'code': 200,
            'msg': '获取成功',
            'data': data
        })
    else:
        return JsonResponse({
            'code': 400,
            'msg': '获取失败',
            'data': {}
        })




# 返回CSRF Token
def get_csrf_token_view(request):
    csrf_token = get_token(request)
    response = JsonResponse({'CSRF': csrf_token})
    response.headers['CSRF'] = csrf_token
    return response